package interfaces;

import java.util.ArrayList;
import java.util.Collection;

import org.fenggui.binding.render.ImageFont;

import interfaces.superWidgets.InterfaceLabel;
import interfaces.superWidgets.TextWidget;

public class WordWrapHelper {
	
	public static Collection<InterfaceLabel> getCentricLabels(InterfaceLabel sourceLabel, String text) {
		Collection<InterfaceLabel> labels = new ArrayList<InterfaceLabel>();
		
		WordWrapHelper.wrapWords(sourceLabel, text);
		
		String[] parts = sourceLabel.getText().split("\n");
		ImageFont font = sourceLabel.getFont();
		int lineHeight = font.getHeight();
		int lines = parts.length;
		int contentHeight = lines * lineHeight;
		int width = sourceLabel.getWidth();
		
		for(int i = 0; i < lines; i++) {
			String lineString = parts[i];
			int labelX = (width - font.getWidth(lineString)) / 2;
			int labelY = contentHeight - ((i + 1) * lineHeight);
			
			InterfaceLabel label = new InterfaceLabel(lineString, font);
			label.setSize(width, lineHeight);
			label.setXY(labelX, labelY);
			labels.add(label);
		}
		
		return labels;
	}
	
	public static void wrapWords(TextWidget label, String text) {
		ImageFont font = label.getFont();
		label.setMultiline(true);
		
		WordWrap wrap = new WordWrap(font, text, label.getWidth());
		int next = wrap.next();
		StringBuilder builder = new StringBuilder(text);
				
		int i = 0;
		while(next > 0 && next < text.length()) {
			builder.insert(next + i, '\n');
			next = wrap.next();
			i++;
		}
		
		label.setText(builder.toString());
		label.setHeight(font.getHeight() * (i + 1));
	}
}